<template>
  <el-row :gutter="20">
    <el-col :lg="6" :md="8" :sm="12" :xs="24" style="height: 100%">
      <el-card class="box-card fix-el-card" shadow="hover">
        <template #header>
          <span>{{ t("code.dictionary") }}</span>
          <span>
            <el-button class="button" link @click="handleTreeClearSelect">{{
              t("common.deselect")
            }}</el-button>
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="t('common.refreshButton')"
              placement="top"
            >
              <el-button class="button" link @click="handleCodeRefresh">
                <el-icon :size="18">
                  <ico-svg icon="grid-refresh-line"></ico-svg>
                </el-icon> </el-button
            ></el-tooltip>
          </span>
        </template>
        <el-tree
          v-if="state.refresh"
          ref="treeRef"
          node-key="codeId"
          :props="treeProps"
          :load="lazyLoadNode"
          @current-change="onTreeNodeCurrentChange"
          lazy
        />
      </el-card>
    </el-col>
    <el-col :lg="18" :md="16" :sm="12" :xs="24">
      <data-grid
        ref="dataGridRef"
        id="admin-code-grid"
        row-key="codeId"
        defaultSort="ascending"
        defaultSortBy="levelCode"
        :request="handleLoadGrid"
        :columns="state.columns"
        :buttons="state.buttons"
      >
        <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
        <template #button-primary="button">
          <el-button
            size="mini"
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            >{{ t("code.newDictionaryButton") }}</el-button
          >
        </template>
        <template #button-search="button">
          <el-input
            v-model="formSearch.searchValue"
            class="fix-input-with-select"
            :suffix-icon="Search"
            @keyup.enter.native="handleSearch"
          >
            <template #prepend>
              <el-select v-model="formSearch.searchField" style="width: 110px">
                <el-option :label="t('code.name')" value="name"></el-option>
                <el-option :label="t('code.code')" value="code"></el-option>
                <el-option :label="t('code.value')" value="value"></el-option>
                <el-option
                  :label="t('code.extended')"
                  value="extended"
                ></el-option>
              </el-select>
            </template>
          </el-input>
        </template>

        <!-- 自定义模板，会替换控件中的 tdSlot，模板 status 仅在当前作用域有效 -->
        <template #visible="slotProps">
          <el-switch
            v-model="slotProps.row.visible"
            :active-value="1"
            :inactive-value="0"
            @change="handleStateChange($event, slotProps.row)"
          />
        </template>

        <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
        <template #operate="slotProps">
          <el-link type="primary" @click="handleEdit(slotProps.row)">{{
            t("common.editButton")
          }}</el-link>
          &nbsp;
          <el-link
            type="primary"
            :title="slotProps.item.title"
            @click="handleDelete(slotProps.row)"
            >{{ t("common.deleteButton") }}
          </el-link>
        </template>
      </data-grid>
    </el-col>
  </el-row>

  <edit-form ref="editFormRef" @on-submit-success="onSubmitSuccess"></edit-form>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import utils from "../../../utils/utils";
import apiCode from "../api/code";
import { useRouter } from "vue-router";
import CodeTreeNode from "./tree-node";
import Node from "element-plus/es/components/tree/src/model/node";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });

const router = useRouter();
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
const viewFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);
const treeRef = ref();
const treeProps = {
  label: "name",
  children: "children",
  isLeaf: "leaf",
};

// 查询区域表单数据
const formSearch = reactive({
  searchField: "name",
  searchValue: "",
  parentId: "",
});

const state = reactive({
  refresh: true,
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      title: () => t("code.name"),
      field: "name",
      sortable: true,
      resizable: true,
    },
    {
      title: () => t("code.code"),
      field: "code",
      sortable: true,
      resizable: true,
    },
    {
      title: () => t("code.value"),
      field: "value",
      showOverflowTooltip: true,
      sortable: true,
      resizable: true,
    },
    {
      title: () => t("code.levelCode"),
      field: "levelCode",
      showOverflowTooltip: true,
      sortable: true,
      resizable: true,
      hidden: true,
    },
    {
      title: () => t("code.extended"),
      field: "extended0",
      showOverflowTooltip: true,
      sortable: true,
      resizable: true,
      hidden: true,
    },
    {
      title: () => t("code.extended"),
      field: "extended1",
      sortable: true,
      resizable: true,
      hidden: true,
    },
    {
      title: () => t("code.visible"),
      field: "visible",
      tdSlot: "visible",
      width: 100,
      hidden: true,
    },
    {
      title: () => t("common.operateButton"),
      field: "opId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
    {
      type: "primary",
      buttonSlot: "button-search",
    },
  ],
  row: null,
});

const handleCodeRefresh = () => {
  state.refresh = false;
  setTimeout(() => {
    state.refresh = true;
  }, 10);
};
const lazyLoadNode = async (node: Node, resolve: any) => {
  if (node.level === 0) {
    let treeData = await apiCode.loadChilds("0");
    // treeData.forEach((m: any) => {
    //   m.name = m.name + "-" + m.code;
    // });
    // console.log("node.level === 0", treeData);
    return resolve(treeData);
  } else {
    if (node.data.leaf) {
      resolve([]);
    }
    let treeData = await apiCode.loadChilds(node.data.codeId);
    // treeData.forEach((m: any) => {
    //   m.name = m.name + "-" + m.code;
    // });
    return resolve(treeData);
  }
};
const onTreeNodeCurrentChange = (data: CodeTreeNode, node: Node) => {
  // console.log("onTreeNodeCurrentChange", data, node);
  formSearch.parentId = data.codeId;
  handleSearch();
};
const handleTreeClearSelect = () => {
  treeRef.value.setCurrentKey(null);
  formSearch.parentId = "";
  handleSearch();
};

// 加载数据
const handleLoadGrid = async (params: any) => {
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiCode
    .queryCodeListing(params)
    .then((response: any) => {
      data = response.data;
    })
    .catch((err: any) => {
      utils.errorNotification("数据处理错误", err);
    });

  // 返回数据给表格组件
  return data;
};

// 删除操作事件
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除代码“${row.name}”及全部下级代码吗?`, {
    confirmButtonText: t("common.okButton"),
    cancelButtonText: t("common.cancelButton"),
  })
    .then(() => {
      apiCode
        .deleteCode(row.codeId)
        .then((response: any) => {
          if (response.data.code == 200) {
            handleSearch();
            handleCodeRefresh();
            utils.infoNotification(`代码“${row.name}”已删除`);
          }
        })
        .catch((err: any) => {
          utils.errorNotification("数据处理错误", err);
        });
    })
    .catch((err: any) => {});
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开编辑页
const handleEdit = (row: any) => {
  editFormRef.value.show(row);
};
// 新增、编辑页确定按钮回调事件
const onSubmitSuccess = (result: boolean) => {
  handleSearch();
  handleCodeRefresh();
};

const handleStateChange = (visible: any, row: any) => {
  // console.log("handleStateChange", state, row);
  if (row.codeId != undefined) {
    // 避免第一次加载页面触发
    apiCode
      .changeCodeVisible(row.codeId, visible == 1 ? 1 : 0)
      .then((response: any) => {
        if (response.data.code == 200) {
        }
      })
      .catch((err: any) => {
        utils.errorNotification("数据处理错误", err);
      });
  }
};

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
</script>
<style scoped>
.el-card {
  border-radius: 0;
  border: none;
}
</style>
<style>
/* 在表格区域的选择输入框 */
.fix-input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.fix-input-with-select,
.fix-input-with-select * {
  border-radius: 0;
}
</style>
